// https://www.acwing.com/problem/content/846/

#include <iostream>
#include <queue>

using namespace std;

// 这是一个超时的解法。。。。。。查了相关资料，不得不放弃 DFS

int m, n;
int board[105][105];
int dist[105][105];  // 记录每个节点的最短步数，这里还做了一个 trick 如果是 -1 则表示还没有访问过
int to[4][2] = {{0, -1}, {1, 0}, {-1, 0}, {0, 1}};

void bfs() {
    queue<pair<int, int>> que;
    que.push({0, 0});
    dist[0][0] = 0;
    while (!que.empty()) {
        auto [x, y] = que.front();
        if (x == m - 1 && y == n - 1) {
            return;
        }
        que.pop();
        for (auto &t: to) {
            int tx = x + t[0], ty = y + t[1];
            if (tx >= 0 && ty >= 0 && tx < m && ty < n && !board[tx][ty] && dist[tx][ty] == -1) {
                que.push({tx, ty});
                dist[tx][ty] = dist[x][y] + 1;
            }
        }
    }
}
/*
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

[8]

10 10
0 0 0 0 0 0 1 0 0 1
0 0 1 0 0 1 0 0 0 1
0 0 1 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0
1 1 1 0 0 0 0 1 0 0
0 0 0 0 0 0 1 0 0 1
0 0 0 1 1 1 0 1 1 1
0 0 0 0 0 0 0 0 0 1
0 0 0 0 1 0 1 0 0 0
0 0 0 0 1 0 1 1 1 0

[20]
*/
int main() {
    scanf("%d%d", &m, &n);
    for (int i=0; i<m; i++) {
        for (int j=0; j<n; j++) {
            scanf("%d", &board[i][j]);
        }
    }
    memset(dist, -1, sizeof dist);
    bfs();
    cout<<dist[m-1][n-1]<<endl;
    return 0;
}
